#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:read_grammar.py
# author:邹煜扬
# datetime:2024/12/17 18:04
# software: PyCharm
"""
读取文件中的文法并用相应的数据结构保存
"""
# import module your need
import re

from models.grammar import Grammar
from models.production import Production

class ReadGrammar:
    def __init__(self,file_path):
        self.file_path = file_path
        self.read()

    def read(self):
        grammar = Grammar()
        with open(self.file_path,'r',encoding='utf-8') as file:#读取文法文件
            lines = file.readlines()
            deduce = re.compile(r'->')#正则表达式匹配->

            first_line_processed = False  # 添加一个标志来标记是否处理了第一行

            for line in lines:#遍历文件中的每一行
                line = line.strip()#去除行首行尾的空格和换行符
                if line == '':#如果行为空，跳过
                    continue

                if not first_line_processed:  # 如果是第一行，单独处理
                    match = re.search(r'G\[(.*?)\]', line)
                    if match:
                        grammar.set_start_symbol(match.group(1))
                    else:
                        raise Exception('文法有误，请检查第一行，格式应为G[开始符号]')
                    first_line_processed = True  # 标记第一行已被处理
                    continue  # 跳过后面的代码，直接进入下一轮循环

                match = re.match(r'(\w+)\s*->\s*(.*?)\s*$', line)
                if match:
                    left= match.group(1)
                    right_sides = match.group(2)
                    left = left.strip()#去除左部的空格
                    right_sides = right_sides.strip()#去除右部的空格
                    right_sides = right_sides.split('|')#将右部以|分割成多个产生式
                    for right in right_sides:
                        grammar.add_production(left,right)#将产生式添加到文法中
                else:#如果行中不包含->，说明文法有误
                    raise Exception('文法有误，请检查第{}行'.format(lines.index(line)+1))
        return grammar



